#!/usr/bin/env node

const bcrypt = require('bcryptjs');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log('🔐 OKX Trading Robot - 密码生成工具');
console.log('=====================================\n');

function generatePasswordHash(password) {
  const saltRounds = 10;
  const hash = bcrypt.hashSync(password, saltRounds);
  return hash;
}

function verifyPassword(password, hash) {
  return bcrypt.compareSync(password, hash);
}

function generateRandomPassword(length = 12) {
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
  let password = '';
  for (let i = 0; i < length; i++) {
    password += charset.charAt(Math.floor(Math.random() * charset.length));
  }
  return password;
}

async function main() {
  try {
    console.log('请选择操作:');
    console.log('1. 生成密码哈希');
    console.log('2. 验证密码');
    console.log('3. 生成随机密码');
    console.log('4. 生成管理员密码哈希');
    console.log('5. 退出\n');

    rl.question('请输入选择 (1-5): ', async (choice) => {
      switch (choice.trim()) {
        case '1':
          await generateHash();
          break;
        case '2':
          await verifyHash();
          break;
        case '3':
          await generateRandom();
          break;
        case '4':
          await generateAdminHash();
          break;
        case '5':
          console.log('👋 再见！');
          rl.close();
          return;
        default:
          console.log('❌ 无效选择，请重新输入\n');
          main();
          return;
      }
    });
  } catch (error) {
    console.error('❌ 发生错误:', error.message);
    rl.close();
  }
}

async function generateHash() {
  rl.question('请输入密码: ', (password) => {
    if (!password.trim()) {
      console.log('❌ 密码不能为空\n');
      main();
      return;
    }

    const hash = generatePasswordHash(password);
    console.log('\n✅ 密码哈希生成成功:');
    console.log('密码:', password);
    console.log('哈希:', hash);
    console.log('\n📝 使用说明:');
    console.log('1. 将此哈希值复制到数据库初始化脚本中');
    console.log('2. 替换默认的密码哈希');
    console.log('3. 重新运行数据库初始化\n');

    main();
  });
}

async function verifyHash() {
  rl.question('请输入密码: ', (password) => {
    rl.question('请输入哈希值: ', (hash) => {
      if (!password.trim() || !hash.trim()) {
        console.log('❌ 密码和哈希值不能为空\n');
        main();
        return;
      }

      const isValid = verifyPassword(password, hash);
      console.log('\n🔍 验证结果:');
      console.log('密码:', password);
      console.log('哈希:', hash);
      console.log('验证结果:', isValid ? '✅ 正确' : '❌ 错误');
      console.log('');

      main();
    });
  });
}

async function generateRandom() {
  rl.question('请输入密码长度 (默认12): ', (length) => {
    const len = parseInt(length) || 12;
    if (len < 8) {
      console.log('⚠️  密码长度建议至少8位\n');
      main();
      return;
    }

    const password = generateRandomPassword(len);
    const hash = generatePasswordHash(password);

    console.log('\n🎲 随机密码生成成功:');
    console.log('密码:', password);
    console.log('哈希:', hash);
    console.log('\n📝 使用说明:');
    console.log('1. 请保存好生成的密码');
    console.log('2. 将哈希值复制到数据库初始化脚本中');
    console.log('3. 重新运行数据库初始化\n');

    main();
  });
}

async function generateAdminHash() {
  console.log('\n🔧 生成管理员密码哈希');
  console.log('这将生成一个安全的随机密码用于管理员账户\n');

  rl.question('是否生成随机管理员密码？(y/n): ', (answer) => {
    if (answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes') {
      const password = generateRandomPassword(16);
      const hash = generatePasswordHash(password);

      console.log('\n👑 管理员密码生成成功:');
      console.log('用户名: admin');
      console.log('邮箱: admin@okx-robot.com');
      console.log('密码:', password);
      console.log('哈希:', hash);
      console.log('\n📝 使用说明:');
      console.log('1. 请立即保存此密码！');
      console.log('2. 将哈希值替换到数据库初始化脚本中');
      console.log('3. 重新运行数据库初始化');
      console.log('4. 使用新密码登录系统\n');
    } else {
      console.log('❌ 操作已取消\n');
    }

    main();
  });
}

// 启动程序
main();

// 处理程序退出
process.on('SIGINT', () => {
  console.log('\n👋 再见！');
  rl.close();
  process.exit(0);
});
